package test.server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONObject;

import test.client.GreetingService;

import com.google.appengine.api.datastore.Entity;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService
{

  public String greetServer(String input) throws IllegalArgumentException
  {
    try
    {
    input = escapeHtml(input);
    
    //add a db entry
    SearchQuery query = new SearchQuery(input, new Date());
    query.createOrUpdateQuery();
    
    StringBuilder output = new StringBuilder();
    URL nasa = new URL("http://data.nasa.gov/api/get_search_results/?search=" + input);
    URLConnection connection = nasa.openConnection();
    connection.setReadTimeout(100000);
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null)
    {
      output.append(inputLine);
    }
    in.close();

    JSONObject jObj = new JSONObject(output.toString());
    Iterator it = jObj.keys();
    String results = "";
    while (it.hasNext())
    {
      String key = (String) it.next();
      Object o = jObj.get(key);
      if (key.equalsIgnoreCase("posts"))
      {
        results = getResults(o);
      }
    }
    System.out.println(results);
    return results;
    }
    catch(Exception e)
    {
     return e.getMessage();
    }
    
  }

  private static String getResults(Object o) throws Exception
  {
    StringBuffer result = new StringBuffer();
    if (o instanceof JSONArray)
    {
      for (int i = 0; i < ((JSONArray) o).length(); i++)
      {
        if (((JSONArray) o).get(i) instanceof JSONObject)
        {
          JSONObject temp = (JSONObject) ((JSONArray) o).get(i);
          Result tempResult = new Result();
          Iterator it = temp.keys();
          while (it.hasNext())
          {
            String keyTemp = (String) it.next();
            Object oTemp = temp.get(keyTemp);
            if (keyTemp.equalsIgnoreCase("content"))
            {
              tempResult.setContent((String) oTemp);
            }
            else if (keyTemp.equalsIgnoreCase("title"))
            {
              tempResult.setTitle((String) oTemp);
            }
            else if (keyTemp.equalsIgnoreCase("url"))
            {
              tempResult.setUrl((String) oTemp);
            }
          }
          result.append(tempResult.toHTML());
        }
      }
    }
    return result.toString();
  }

  private String escapeHtml(String html)
  {
    if (html == null)
    {
      return null;
    }
    return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
  }

  
  public String showServer(String input) throws IllegalArgumentException
  {
    try
    {
      StringBuffer results = new StringBuffer();
      
      Iterable<Entity> searchQueriesSaved = SearchQueryUtil.getAllQueries();
      
      if(searchQueriesSaved != null)
      {
        for(Entity entity : searchQueriesSaved)
        {
          results.append((new SearchQuery((String)entity.getProperty("query"), (Date)entity.getProperty("date"))).toHTML());
        }
      }
      
      return results.toString();
    }
    catch(Exception e)
    {
     return e.getMessage();
    }
    
  }
}
